package com.atguigu.flink.chapter11;

import com.atguigu.flink.bean.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.Over;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.*;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2021/8/20 10:54
 */
public class Flink21_Table_Over_Window {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        
        // 1. 先创建一流
        DataStream<WaterSensor> waterSensorStream =
            env.fromElements(new WaterSensor("sensor_1", 1000L, 10),
                             new WaterSensor("sensor_1", 4000L, 20),
                             new WaterSensor("sensor_1", 4000L, 40),
                             new WaterSensor("sensor_1", 5000L, 50)
//                             new WaterSensor("sensor_2", 3000L, 30),
//                             new WaterSensor("sensor_2", 6000L, 60)
            )
                .assignTimestampsAndWatermarks(
                    WatermarkStrategy
                        .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                        .withTimestampAssigner((ws, ts) -> ws.getTs())
                );
        
        // 2. 把流转成一个动态表
        StreamTableEnvironment tenv = StreamTableEnvironment.create(env);
        Table table = tenv.fromDataStream(waterSensorStream, $("id"), $("ts").rowtime(), $("vc"));
       
        table
//            .window(Over.partitionBy($("id")).orderBy($("ts")).preceding(UNBOUNDED_ROW).as("w"))
//            .window(Over.partitionBy($("id")).orderBy($("ts")).preceding(rowInterval(1L)).as("w"))
//            .window(Over.partitionBy($("id")).orderBy($("ts")).preceding(UNBOUNDED_RANGE).as("w"))
            .window(Over.partitionBy($("id")).orderBy($("ts")).preceding(lit(3).second()).as("w"))
            .select($("id"), $("ts"), $("vc"), $("vc").sum().over($("w")).as("sum_vc"))
            .execute()
            .print();
        
        env.execute();
        
    }
}
